package com.tim.android.utils;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public final class ResourcesUtil {
	
	private static final String FOLDER_NAME = "tim_widget";

	private ResourcesUtil() {
		
	}
	
	public static Drawable getDrawableFromXML(Context context, String fileName) {
		Drawable drawable = null;
		InputStream inputStream = null;
		try {
			XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
			inputStream = context.getResources().getAssets().
					open(FOLDER_NAME + "/" + fileName);
			parser.setInput(inputStream, null);
			drawable = Drawable.createFromXml(context.getResources(), parser);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} finally {
			closeInputStream(inputStream);
		}
		return drawable;
	}
	
	public static Drawable getDrawable(Context context, String fileFullName) {
		Drawable drawable = null;
		drawable = new BitmapDrawable(getBitmap(context, fileFullName));
		return drawable;
	}
	
	public static Bitmap getBitmap(Context context, String fileFullName) {
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			 is = context.getResources().getAssets().
					open(FOLDER_NAME + "/" + fileFullName);
			bitmap = BitmapFactory.decodeStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeInputStream(is);
		}
		return bitmap;
	}
	
	private static void closeInputStream(InputStream is) {
		try {
			if(is != null) {
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
